package com.lykj.llw.box.ui.fragment

import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import app.dinus.com.itemdecoration.LinearDividerItemDecoration
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.FitCenter
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseFragment
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.home.HomeHotGameAdapter
import com.lykj.llw.box.adapter.home.HomeNewAdapter
import com.lykj.llw.box.adapter.home.HomeTopGameAdapter
import com.lykj.llw.box.adapter.home.HomeVipGameAdapter
import com.lykj.llw.box.data.bean.response.CheckUpdateResponse
import com.lykj.llw.box.data.bean.response.HomeBannerResponse
import com.lykj.llw.box.data.bean.response.HomeResponse
import com.lykj.llw.box.data.bean.response.HomeVipGameResponse
import com.lykj.llw.box.data.bean.response.ServerConfigResponse
import com.lykj.llw.box.databinding.FrgHomeBinding
import com.lykj.llw.box.ui.activity.CheckUpdateActivity
import com.lykj.llw.box.ui.activity.DownloadManagerActivity
import com.lykj.llw.box.ui.activity.GameDetailActivity
import com.lykj.llw.box.ui.activity.GameSearchActivity
import com.lykj.llw.box.ui.activity.HotGameLookMoreActivity
import com.lykj.llw.box.ui.activity.MobileLoginActivity
import com.lykj.llw.box.ui.activity.PlayedGameActivity
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.listener.OnPageChangeListener
import io.reactivex.disposables.Disposable
import me.jessyan.autosize.utils.AutoSizeUtils
import okhttp3.ResponseBody


/**
 * ================================================
 * Frag-首页
 * ================================================
 *
 * @author gosha
 * @date 2023/10/12-18:06
 */
class HomeFragment : BaseFragment() {
    lateinit var binding: FrgHomeBinding

    private val TAG = "Home"

    private var mIsRecommend = true


    //排行榜
    private val mTopGameAdapter = HomeTopGameAdapter()
    private val mTopGames = ArrayList<HomeResponse.DataDTO.SortGameListDTO>()

    //精选游戏
    private val mHotGameAdapter = HomeHotGameAdapter()
    private val mHotGames = ArrayList<HomeResponse.DataDTO.HotGameListDTO>()

    //最新游戏
    private val mNewGameAdapter = HomeNewAdapter()
    private val mNewGames = ArrayList<HomeResponse.DataDTO.NewGameListDTO>()

    private val mVipGameAdapter = HomeVipGameAdapter()
    private val mVipGames = ArrayList<HomeVipGameResponse.DataDTO>()

    //顶部轮播
    private val mTopGameCovers = ArrayList<HomeResponse.DataDTO.TopGameListDTO>()

    //今日首发的游戏id
    private var gid = -1

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FrgHomeBinding.inflate(layoutInflater)
        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false).init()
    }

    override fun initUI() {
        GlideApp.with(this)
            .load(R.drawable.gif_vip)
            .transition(DrawableTransitionOptions.withCrossFade())
            .into(binding.ivVipGame)

        GlideApp.with(this)
            .load(R.mipmap.mask_home)
            .apply(
                RequestOptions.bitmapTransform(
                    RoundedCorners(
                        AutoSizeUtils.dp2px(
                            requireContext(), 7.5f
                        )
                    )
                )
            )
            .transition(DrawableTransitionOptions.withCrossFade())
            .into(binding.ivMask)

        initRecyclerView()

        statusTabChange()
    }

    private fun initRecyclerView() {
        initTopRCV()
        initHotRCV()
        initHewRCV()
        initVipRCV()
    }

    private fun initTopRCV() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvTopGame.layoutManager = linearLayoutManager
        binding.rcvTopGame.setHasFixedSize(true)
        mTopGameAdapter.data = mTopGames
        mTopGameAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), GameDetailActivity::class.java)
            intent.putExtra("gid", mTopGames[position].gid)
            startActivity(intent)
        }
        binding.rcvTopGame.adapter = mTopGameAdapter
    }

    private fun initHotRCV() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvFeaturedGame.layoutManager = linearLayoutManager
        binding.rcvFeaturedGame.setHasFixedSize(true)
        val dividerItemDecoration = LinearDividerItemDecoration(
            requireContext(), LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_10dp, resources.newTheme()
            )
        )
        binding.rcvFeaturedGame.addItemDecoration(dividerItemDecoration)
        mHotGameAdapter.data = mHotGames
        mHotGameAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), GameDetailActivity::class.java)
            intent.putExtra("gid", mHotGames[position].gid)
            startActivity(intent)
        }
        binding.rcvFeaturedGame.adapter = mHotGameAdapter
    }

    private fun initVipRCV() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvVipGame.layoutManager = linearLayoutManager
        binding.rcvVipGame.setHasFixedSize(true)
        mVipGameAdapter.data = mVipGames
        mVipGameAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), GameDetailActivity::class.java)
            intent.putExtra("gid", mVipGames[position].gid)
            startActivity(intent)
        }
        val dividerItemDecoration = LinearDividerItemDecoration(
            requireContext(), LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_10dp, resources.newTheme()
            )
        )
        binding.rcvVipGame.addItemDecoration(dividerItemDecoration)
        binding.rcvVipGame.adapter = mVipGameAdapter
    }

    private fun initHewRCV() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvNewGame.layoutManager = linearLayoutManager
        binding.rcvNewGame.setHasFixedSize(true)
        mNewGameAdapter.data = mNewGames
        mNewGameAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(requireContext(), GameDetailActivity::class.java)
            intent.putExtra("gid", mNewGames[position].gid)
            startActivity(intent)
        }
        binding.rcvNewGame.adapter = mNewGameAdapter
    }

    //获取首页Banner
    private fun obtainHomeBanner() {
        RetrofitManager.instance.obtainHomeBanner(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@HomeFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                dealWithHomeBanner(responseBody)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //处理首页banner
    private fun dealWithHomeBanner(str: String) {
        val bean = GsonUtils.fromJson(str, HomeBannerResponse::class.java)

        if (!bean.data.isNullOrEmpty()) {
            setBanner(bean.data)
        }
    }

    //获取首页数据
    private fun obtainHomeData() {
        RetrofitManager.instance.obtainHome(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@HomeFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                dealWithHomeData(responseBody)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //处理首页数据
    private fun dealWithHomeData(str: String) {
        val bean = GsonUtils.fromJson(str, HomeResponse::class.java)
        mTopGameCovers.clear()
        if (bean.data.topGameList.isNotEmpty()) {
            mTopGameCovers.addAll(bean.data.topGameList)

            if (bean.data.topGameList.size >= 1) {
                binding.ivCover1.visibility = View.VISIBLE
                GlideApp.with(this@HomeFragment)
                    .load(bean.data.topGameList[0].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivCover1)
            } else {
                binding.ivCover1.visibility = View.GONE
            }

            if (bean.data.topGameList.size >= 2) {
                binding.ivCover2.visibility = View.VISIBLE
                GlideApp.with(this@HomeFragment)
                    .load(bean.data.topGameList[1].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivCover2)
            } else {
                binding.ivCover2.visibility = View.GONE
            }

            if (bean.data.topGameList.size >= 3) {
                binding.ivCover3.visibility = View.VISIBLE
                GlideApp.with(this@HomeFragment)
                    .load(bean.data.topGameList[2].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivCover3)
            } else {
                binding.ivCover3.visibility = View.GONE
            }

            if (bean.data.topGameList.size == 4) {
                binding.ivCover4.visibility = View.VISIBLE
                GlideApp.with(this@HomeFragment)
                    .load(bean.data.topGameList[3].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivCover4)
            } else {
                binding.ivCover4.visibility = View.GONE
            }

            setBannerCover(bean.data.topGameList)
            switchBanner(0, false)
        }
        mHotGames.clear()
        if (bean.data.hotGameList.isNotEmpty()) {
            mHotGames.addAll(bean.data.hotGameList)
        }
        mNewGames.clear()
        if (bean.data.newGameList.isNotEmpty()) {
            //截取大于三个的列表数据
            if (bean.data.newGameList.size > 3) {
                mNewGames.addAll(
                    bean.data.newGameList.subList(
                        3, bean.data.newGameList.size
                    )
                )
            }
            if (bean.data.newGameList.size >= 1) {
                setNewGameTop(1, bean.data.newGameList)
            }
            if (bean.data.newGameList.size >= 2) {
                setNewGameTop(2, bean.data.newGameList)
            }
            if (bean.data.newGameList.size >= 3) {
                setNewGameTop(3, bean.data.newGameList)
            }
            binding.ivNewDesc.visibility = View.VISIBLE
        } else {
            binding.ivNewDesc.visibility = View.GONE
        }
        mTopGames.clear()
        if (bean.data.sortGameList.isNotEmpty()) {
            mTopGames.addAll(bean.data.sortGameList)
        }

        //今日首发
        if (null != bean.data.todayFirstGame) {
            gid = bean.data.todayFirstGame.gid

            binding.cltTodayStater.visibility = View.VISIBLE
            binding.tvStartTodayGameName.text = "${bean.data.todayFirstGame.gamename}"
            binding.tvStartTodayLabel.text =
                "${bean.data.todayFirstGame.collection} ${bean.data.todayFirstGame.gametype} ${bean.data.todayFirstGame.gameSize}"
            binding.tvStartTodaySummery.text = "${bean.data.todayFirstGame.subject}"

            GlideApp.with(this)
                .load(bean.data.todayFirstGame.icon)
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(binding.ivStartTodayIcon)

            if (bean.data.todayFirstGame.payRatio == 0.01) {
                binding.ivIvStartTodayDiscount.visibility = View.VISIBLE
            } else {
                binding.ivIvStartTodayDiscount.visibility = View.GONE
            }
        } else {
            binding.cltTodayStater.visibility = View.GONE
        }

        mTopGameAdapter.notifyDataSetChanged()
        mHotGameAdapter.notifyDataSetChanged()
        mNewGameAdapter.notifyDataSetChanged()
    }

    //获取首页vip游戏列表
    private fun obtainHomeVipGames() {
        RetrofitManager.instance.obtainHomeVipGames(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@HomeFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, HomeVipGameResponse::class.java)

                mVipGames.clear()
                if (!bean.data.isNullOrEmpty()) {
                    mVipGames.addAll(bean.data)
                }

                mVipGameAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //检查是否需要更新
    private fun checkUpdate() {
        RetrofitManager.instance.checkUpdate(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@HomeFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, CheckUpdateResponse::class.java)
                val intent = Intent(requireContext(), CheckUpdateActivity::class.java)
                intent.putExtra("title", "${bean.data.name}")
                intent.putExtra("url", bean.data.url)
                intent.putExtra("content", "${bean.data.subject}")

                if (bean.data.appVersion.toInt() > PackageUtils.getVersionCode(requireContext())) {
                    //TODO:判断是否需要更新
                    if (bean?.data?.isForce == 1) {//强制更新
                        intent.putExtra("forcedUpdate", true)
                        startActivity(intent)
                    } else if (!bean?.data?.url.isNullOrBlank()) {//url,不为空
                        intent.putExtra("forcedUpdate", false)
                        startActivity(intent)
                    }
                } else {
                    Log.e(TAG, "不需要更新")
                }
            }

            override fun handleException(ret: String, msg: String?) {
                LogUtils.e(msg)
            }
        })
    }

    //设置最新游戏的顶部显示
    private fun setNewGameTop(index: Int, list: List<HomeResponse.DataDTO.NewGameListDTO>) {
        when (index) {
            1 -> {
                binding.cltNew1.visibility = View.VISIBLE
                binding.tvNewLabel1.text = "${list[0].collection} ${list[0].gametype}"
                binding.tvNewName1.text = "${list[0].gamename}"
                binding.tvTime1.text = "${list[0].openTime}"

                GlideApp.with(this)
                    .load(list[0].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivNew1)

                binding.cltNew1.clickWithTrigger {
                    val intent = Intent(requireContext(), GameDetailActivity::class.java)
                    intent.putExtra("gid", list[0].gid)
                    startActivity(intent)
                }
            }

            2 -> {
                binding.cltNew2.visibility = View.VISIBLE
                binding.tvNewLabel2.text = "${list[1].collection} ${list[1].gametype}"
                binding.tvNewName2.text = "${list[1].gamename}"
                binding.tvTime2.text = "${list[1].openTime}"

                GlideApp.with(this)
                    .load(list[1].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivNew2)

                binding.cltNew2.clickWithTrigger {
                    val intent = Intent(requireContext(), GameDetailActivity::class.java)
                    intent.putExtra("gid", list[1].gid)
                    startActivity(intent)
                }
            }

            3 -> {
                binding.cltNew3.visibility = View.VISIBLE
                binding.tvNewLabel3.text = "${list[2].collection} ${list[2].gametype}"
                binding.tvNewName3.text = "${list[2].gamename}"
                binding.tvTime3.text = "${list[2].openTime}"

                GlideApp.with(this)
                    .load(list[2].icon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivNew3)

                binding.cltNew3.clickWithTrigger {
                    val intent = Intent(requireContext(), GameDetailActivity::class.java)
                    intent.putExtra("gid", list[2].gid)
                    startActivity(intent)
                }
            }
        }
    }

    //设置banner
    private fun setBanner(list: List<HomeBannerResponse.DataDTO>) {
        binding.bannerHome.setStartPosition(0)
            .setAdapter(object : BannerImageAdapter<HomeBannerResponse.DataDTO?>(list) {
                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: HomeBannerResponse.DataDTO?,
                    position: Int,
                    size: Int
                ) {
                    //图片加载自己实现
                    GlideApp.with(holder!!.itemView).load(data?.pic).apply(
                        RequestOptions.bitmapTransform(
                            RoundedCorners(
                                AutoSizeUtils.dp2px(
                                    requireContext(), 7.5f
                                )
                            )
                        )
                    )
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(holder!!.imageView)
                }
            }).setOnBannerListener { data, position ->
                val item = data as HomeBannerResponse.DataDTO
                when (item.type) {
                    1 -> {
                        //跳转详情
                        val intent = Intent(requireContext(), GameDetailActivity::class.java)
                        intent.putExtra("gid", item.gid)
                        startActivity(intent)
                    }

                    2 -> {
                        //跳转url链接
                        try {
                            val intent = Intent()
                            intent.action = "android.intent.action.VIEW"
                            val url = Uri.parse(item.url)
                            intent.data = url
                            startActivity(intent)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }.addBannerLifecycleObserver(this) //添加生命周期观察者
    }

    //设置封面banner
    private fun setBannerCover(list: List<HomeResponse.DataDTO.TopGameListDTO>) {
        val m = MultiTransformation(
            FitCenter(),
            RoundedCorners(
                AutoSizeUtils.dp2px(
                    requireContext(), 7.5f
                )
            ),
        )

        binding.bannerCover
            .setStartPosition(1)
            .setBannerRound(
                AutoSizeUtils.dp2px(
                    requireContext(), 7.5f
                ).toFloat()
            )
            .setAdapter(object : BannerImageAdapter<HomeResponse.DataDTO.TopGameListDTO?>(list) {
                override fun onCreateHolder(parent: ViewGroup?, viewType: Int): BannerImageHolder {
                    val imageView = ImageView(parent!!.context)
                    //注意，必须设置为match_parent，这个是viewpager2强制要求的
                    val params = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    imageView.layoutParams = params
                    return BannerImageHolder(imageView)
                }

                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: HomeResponse.DataDTO.TopGameListDTO?,
                    position: Int,
                    size: Int
                ) {
                    //图片加载自己实现
                    GlideApp.with(holder!!.itemView)
                        .load(data?.bannerPic)
                        .apply(RequestOptions.bitmapTransform(m))
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(holder!!.imageView)
                }
            }).setOnBannerListener { data, position ->
                val intent = Intent(requireContext(), GameDetailActivity::class.java)
                intent.putExtra("gid", mTopGameCovers[position].gid)
                startActivity(intent)
            }
            .addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {

                }

                override fun onPageSelected(position: Int) {
                    switchBanner(position, false)
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
            .addBannerLifecycleObserver(this) //添加生命周期观察者
    }

    private fun restBannerSwitch() {
        val drawable = ColorDrawable(ColorUtils.getColor(android.R.color.transparent))
        binding.ivCover1.background = drawable
        binding.ivCover2.background = drawable
        binding.ivCover3.background = drawable
        binding.ivCover4.background = drawable
    }

    private fun switchBanner(index: Int, unSwitchBanner: Boolean) {
        if (index >= mTopGameCovers.size) {
            return
        }
        restBannerSwitch()

        when (index) {
            0 -> {
                binding.ivCover1.setBackgroundResource(R.drawable.shape_corner_11dp_stroke)
            }

            1 -> {
                binding.ivCover2.setBackgroundResource(R.drawable.shape_corner_11dp_stroke)
            }

            2 -> {
                binding.ivCover3.setBackgroundResource(R.drawable.shape_corner_11dp_stroke)
            }

            3 -> {
                binding.ivCover4.setBackgroundResource(R.drawable.shape_corner_11dp_stroke)
            }
        }

        if (index < mTopGameCovers.size) {
            binding.tvSummery.text = "${mTopGameCovers[index].subject}"
            binding.tvGameName.text = "${mTopGameCovers[index].gamename}"

            binding.fltDiscount.visibility =
                if (mTopGameCovers[index].payRatio == 0.01) View.VISIBLE else View.GONE


            if (unSwitchBanner) {
                binding.bannerCover.setCurrentItem(index + 1, false)
            }
        }
    }

    override fun initData() {
        //优先获取本地缓存,不存在缓存使用请求,页面通过下拉刷新
        val cacheBannerStr = SPUtils.getInstance("api_cache").getString("home_banner")
        val cacheDataStr = SPUtils.getInstance("api_cache").getString("home_data")

        obtainServerConfig()

        if (cacheDataStr.isNullOrBlank()) {
            obtainHomeData()
        } else {
            dealWithHomeData(cacheDataStr)
        }

        if (cacheBannerStr.isNullOrBlank()) {
            obtainHomeBanner()
        } else {
            dealWithHomeBanner(cacheBannerStr)
        }

        if (!BaseApplication.instance?.getUserInfo()?.token.isNullOrBlank()) {
            //检查更新
            checkUpdate()
        }
    }

    //获取服务端配置
    private fun obtainServerConfig() {
        RetrofitManager.instance.obtainServerConfig(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@HomeFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, ServerConfigResponse::class.java)

                FlowBus.with<Boolean>(BConstants.BUS_KEY.HIDE_TRADING)
                    .post(lifecycleScope, bean.data.isShow)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    private fun statusTabChange() {
        val lps = binding.ivVipGame.layoutParams
        if (mIsRecommend) {
            binding.tvRecommend.setTextColor(ColorUtils.getColor(R.color.black))
            binding.tvRecommend.textSize = 17f


            lps.width = AutoSizeUtils.dp2px(requireContext(), 58f)
            lps.height = AutoSizeUtils.dp2px(requireContext(), 19.5f)
            binding.ivVipGame.layoutParams = lps
        } else {
            binding.tvRecommend.setTextColor(ColorUtils.string2Int("#9A9A9A"))
            binding.tvRecommend.textSize = 15f


            lps.width = AutoSizeUtils.dp2px(requireContext(), 61.5f)
            lps.height = AutoSizeUtils.dp2px(requireContext(), 20f)
            binding.ivVipGame.layoutParams = lps
        }
    }

    override fun setListener() {
        binding.ivPlayed.clickWithTrigger {
            if (BaseApplication.instance?.getUserInfo()?.token.isNullOrBlank()) {
                startActivity(Intent(requireContext(), MobileLoginActivity::class.java))
            } else {
                startActivity(Intent(requireContext(), PlayedGameActivity::class.java))
            }
        }

        binding.ivDownloadManger.clickWithTrigger {
            startActivity(Intent(requireContext(), DownloadManagerActivity::class.java))
        }

        binding.lltSearch.clickWithTrigger {
            startActivity(Intent(requireContext(), GameSearchActivity::class.java))
        }

        binding.tvRecommend.clickWithTrigger {
            mIsRecommend = true
            statusTabChange()
            binding.lltRecommend.visibility = View.VISIBLE
            binding.rcvVipGame.visibility = View.GONE
        }
        binding.fltCover1.clickWithTrigger(200) {
            switchBanner(0, true)
        }
        binding.fltCover2.clickWithTrigger(200) {
            switchBanner(1, true)
        }
        binding.fltCover3.clickWithTrigger(200) {
            switchBanner(2, true)
        }
        binding.fltCover4.clickWithTrigger(200) {
            switchBanner(3, true)
        }

        binding.ivVipGame.clickWithTrigger {
            mIsRecommend = false
            statusTabChange()
            binding.lltRecommend.visibility = View.GONE
            binding.rcvVipGame.visibility = View.VISIBLE

            obtainHomeVipGames()
        }

        binding.srfRefresh.setOnRefreshListener {
            obtainServerConfig()
            obtainHomeData()
            obtainHomeBanner()
            obtainHomeVipGames()
            if (!BaseApplication.instance?.getUserInfo()?.token.isNullOrBlank()) {
                //检查更新
                checkUpdate()
            }
            it.finishRefresh(350)
        }

        binding.tvLookMore.clickWithTrigger(200) {
            startActivity(Intent(requireContext(), HotGameLookMoreActivity::class.java))
        }

        binding.cltTodayStater.clickWithTrigger {
            if (gid != -1) {
                val intent = Intent(requireContext(), GameDetailActivity::class.java)
                intent.putExtra("gid", gid)
                startActivity(intent)
            }
        }
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}